﻿using System;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Web.Routing;
using Infrastructure.Web.Mvc.Routing;

namespace Infrastructure.Web.Mvc.Extensions
{
    public static class RouteExtension
    {
        public static void MapRoute(this RouteCollection routes, string name, Regex urlPattern, object defaults)
        {
            routes.MapRoute<RegexRoute>(name, urlPattern, defaults, null);
        }
        public static void MapRoute(this RouteCollection routes, string name, Regex urlPattern, object defaults, string[] namespaces)
        {
            routes.MapRoute<RegexRoute>(name, urlPattern, defaults, namespaces);
        }

        public static void MapRoute<TRoute>(this RouteCollection routes, string name, Regex urlPattern, object defaults) where TRoute : RegexRoute
        {
            routes.MapRoute<TRoute>(name, urlPattern, defaults, null);
        }
        public static void MapRoute<TRoute>(this RouteCollection routes, string name, Regex urlPattern, object defaults, string[] namespaces) where TRoute : RegexRoute
        {
            if (routes == null)
                throw new ArgumentNullException("routes");
            if (urlPattern == null)
                throw new ArgumentNullException("urlPattern");
            Type type = typeof(TRoute);
            ConstructorInfo constructorRoute =type.GetConstructor(new Type[] { typeof(Regex), typeof(RouteValueDictionary), typeof(IRouteHandler) });
            if (constructorRoute != null)
            {
                RegexRoute route = constructorRoute.Invoke(new object[] { urlPattern, new RouteValueDictionary(defaults), new MvcRouteHandler() }) as RegexRoute;

                if (!namespaces.IsEmpty())
                {
                    route.DataTokens = new RouteValueDictionary();
                    route.DataTokens["Namespaces"] = namespaces;
                }

                routes.Add(name, route);
            }
        }
    }
}